<template>
	<view class="content">
		<u-navbar title="设备选择" @leftClick="leftClick" leftIconColor="#fff" rightIconColor="#fff" :autoBack="true"
			rightText="确定" @rightClick="rightClick">
		</u-navbar>

		<view style="font-size: 24px;margin-bottom: 10px;">
			<text>{{TitleName}}</text>
		</view>

		<!-- 吸顶 -- 筛选 -->
		<!-- <u-sticky offset-top="0"> -->
		<view class="SiftBox">
			<view class="SiftBtn">
				<text>新品</text>
			</view>

			<view class="SiftBtn">
				<text @click="open">品牌筛选</text>
			</view>
		</view>
		<!-- </u-sticky> -->

		<!-- 设备列表 -->
		<view style="flex: 1;overflow: auto;">
			<uni-row class="CommonBox" :gutter="20">
				<uni-col style="margin: 10px 0;" v-for="(ReItem,index) in DeviceInfoList" :key="index" :span="ColSpan"
					:md="{span: 6}" :lg="{span: 4}">
					<view class="CommonCard" @click="ChoiceDevice(ReItem)">
						<u-icon v-if="ReItem.BluetoothProtocol == selectedDevice.BluetoothProtocol" class="CheckIcon"
							name="checkbox-mark" color="#fff" size="12px"></u-icon>
						<view>
							<view style="text-align: center;">

								<u--image :showLoading="true" :src="judgeImg(ReItem.FilePath)" mode="widthFix"
									width="50px" height="50px"></u--image>
							</view>
							<view class="TextBox" style="font-size: 16rpx;min-height: 40rpx;">
								<!-- <text class="Text">{{ReItem.BluetoothProtocol}}</text> -->
								<text>{{ReItem.MeasureName}}</text>
								<text>_</text>
								<text>{{ReItem.MeasureSpec}}</text>
							</view>

						</view>
					</view>
				</uni-col>
			</uni-row>


			<!-- 品牌筛选 -->
			<u-popup :show="ShowBrandFiltering" round :safeAreaInsetTop="true" mode="left" @close="close" @open="open">
				<view style="padding: 10px 15px;display: flex;flex-direction: column;"
					:style="`width: ${PopupWidth}px`">

					<!-- <view class="PopupBox"> -->
					<view class="page">
						<view class="wraper">
							<view class="header"
								style="display: flex;justify-content: space-between;align-items: center;">
								<text style="font-size: 20px;font-weight: 600;">品牌筛选</text>

								<u-icon name="close" color="#999" size="18" @click="close"
									style="display: block;width: 50rpx;height: 50px;"></u-icon>

							</view>

							<view id="MainBox" class="main" :style="{height: Height.Main - 50 + 'px'}">
								<scroll-view class="main-scroll" scroll-y style="height: 100%">
									<view class="main-list">

										<view style="text-align: right;">
											<text style="color: #999;margin-left:6px;font-size: 14px;"
												@click="CheckAll">全选</text>

											<text style="color: #999;margin-left:6px;font-size: 14px;">|</text>

											<text style="color: #999;margin-left:6px;font-size: 14px;"
												@click="ResetBtn">重置</text>
										</view>

										<view class="GridList">
											<view class="GridCardBox" v-for="(item,index) in GridBrandList" :key="index"
												@click="CheckedCard(item,index)">
												<view style="margin-top: 40rpx;">
													<u--image :showLoading="true" :src="judgeImg(item.FilePath)"
														mode="widthFix" width="100%" height="60px"></u--image>
												</view>
												<view class="textBox">
													<text>{{item.Brand}}</text>
												</view>


												<u-icon v-if="item.Checked"
													style="position: absolute;top:3px;right:3px;display: block;padding:3px;background: #1aafff;border-radius:50px;"
													name="checkbox-mark" color="#fff" size="12px"></u-icon>
											</view>
										</view>

									</view>
								</scroll-view>
							</view>

							<view class='footer'>
								<view>
									<u-button type="primary" text="筛选" @click="SiftSubBtn"></u-button>
								</view>
							</view>
						</view>
					</view>
					<!-- </view> -->


				</view>
			</u-popup>


		</view>



	</view>
</template>

<script>
	// import TheSonAgreement from '@/static/js/Agreement/5101_Sanhe_YBKC.js'
	export default {
		data() {
			return {
				TitleName: '',
				ClassifyID: '',
				DeviceInfoList: [], // 设备列表
				selectedDevice: {},
				ShowBrandFiltering: false, // 品牌筛选弹窗
				GridBrandList: [], // 品牌筛选列表
				Height: {
					Top: 0,
					Main: 0,
					footer: 0
				},
				ColSpan: 12,
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			var that = this;
			that.TitleName = option.Name;
			that.ClassifyID = option.ClassifyID

			// 获取设备列表数据
			that.GetDeviceInfoArr(option.ClassifyID, '');

			// 获取品牌数据
			that.GetBrandList()

			// uni.$on("sendDeviceType", function(data) {
			// 	that.TitleName = data.DeviceBluetoothTypeName;
			// 	that.GetDeviceInfoArr(data.DeviceBluetoothTypeID);
			// })

		},
		created() {
			// 同步获取系统信息
			let systemInfo = uni.getSystemInfoSync()
			// px转rpx
			// let pxToRpxScale = 750 / systemInfo.windowWidth;
			// 可视窗口宽度
			let ktxWindowWidth = systemInfo.windowWidth
			// console.log(ktxWindowWidth)

			if (ktxWindowWidth <= 500) { // 一行两个
				this.ColSpan = 12
			} else if (ktxWindowWidth > 500 && ktxWindowWidth < 1000) { // 一行三个
				this.ColSpan = 8
			}
		},
		computed: {
			PopupWidth() { // 品牌筛选弹窗 屏幕宽度
				return uni.getSystemInfoSync().screenWidth * (0.8)
			}
		},
		methods: {
			setSwiperHeight(data, Cla) {
				var that = this
				let query = uni.createSelectorQuery().in(this);

				query.select(data).boundingClientRect(); //我找的idimgBox 你的替换就行
				query.exec(res => {
					that.Height[Cla] = res[0].height
				});

			},
			open() { // 品牌筛选弹层打开触发
				var that = this
				// console.log('open');
				that.ShowBrandFiltering = true

				that.$nextTick(() => {
					that.setSwiperHeight('.header', 'Top')
					that.setSwiperHeight('.header', 'footer')

					// console.log(that.Height.Top)
					// console.log(that.Height.footer)

					that.Height.Main = uni.getSystemInfoSync().screenHeight - that.Height.Top - that.Height.footer
					// console.log(uni.getSystemInfoSync().screenHeight)
					// console.log(uni.getSystemInfoSync().screenHeight - that.Height.Top - that.Height.footer)

				});
			},
			CheckedCard(data, index) { // 点击品牌card
				var that = this
				data.Checked = !data.Checked
			},
			CheckAll() { // 全选
				var that = this

				that.GridBrandList.map(item => {
					item.Checked = true
				})
			},
			ResetBtn() { // 重置品牌筛选，将选项还原
				var that = this
				that.GridBrandList.map(item => {
					item.Checked = false
				})
			},
			close() { // 品牌筛选弹层关闭触发
				this.ShowBrandFiltering = false
				// 关闭后重置品牌选项
				this.ResetBtn()
			},
			SiftSubBtn() { // 确认筛选按钮
				var that = this
				// console.log(that.GridBrandList)

				let ChoiceArr = that.GridBrandList.filter(item => {
					return item.Checked
				})

				// 如果筛选弹窗中，选中项数量 == 品牌总数 || == 0，则显示全部； 反之筛选对应数据
				/* 
				 * DeviceInfoList   	显示的列表数据
				 */

				let Ids = ''
				if (ChoiceArr.length == 0 || ChoiceArr.length == that.GridBrandList.length) {
					// 全部，设为空 

				} else {
					let IDs = []
					// 多选，以逗号隔开
					console.log('筛选')
					ChoiceArr.forEach(item => {
						IDs.push(item.EquipmentBrandID)
					})
					Ids = IDs.join(',')
				}

				that.GetDeviceInfoArr(that.ClassifyID, Ids)

				that.close()
			},
			judgeImg(data) {
				var that = this
				console.log(data)
				if (data == null) {
					return ''
				} else if (!/^http[s]?:\/\/.*/.test(data)) {
					return 'http://' + that.Request.serverIP() + data
					// return 'http://' + '39.105.222.87:20000' + data
				} else {
					return data
				}
			},
			GetBrandList() { // 获取品牌数据
				var that = this;
				that.Request.request('selectPPList', {}, function(res) {
					// console.log(res)
					if (res.status == 200) {

						let list = JSON.parse(JSON.stringify(res.data.ds))

						list.forEach(item => {
							item.Checked = false
						})
						that.GridBrandList = list
					}

				})
			},
			GetDeviceInfoArr(ID, Ids) { // 获取设备列表
				var that = this

				let obj = {}

				if (Ids) {
					obj = {
						UpID: ID,
						EquipmentBrandID: Ids
					}
				} else {
					obj = {
						UpID: ID,
					}
				}

				that.Request.request('APP_JLSBLIST', obj, function(res) {
					if (res.status == 200) {

						that.DeviceInfoList = res.data.ds
					}

				})
			},
			ChoiceDevice(data) { // 选中设备
				var that = this;
				that.selectedDevice = data;
			},
			leftClick() { // 返回上一页
				// uni.navigateBack()
			},
			rightClick() { // 点击确认
				var that = this;
				// console.log(that.selectedDevice.BluetoothProtocol)

				if (that.selectedDevice.BluetoothProtocol) {

					// 获取一遍历史存储的设备数据
					// let GetHistoryDevice = uni.getStorageSync('Agreement_History_DevicesList')
					let GetHistoryDevice = that.$store.getters['QmsModule/HistoryDevice']
					// console.log(GetHistoryDevice)

					let Arr = []

					if (GetHistoryDevice.length) { // 如果有数据，去判断是否存储过
						// let TheData = JSON.parse(GetHistoryDevice)
						let TheData = GetHistoryDevice;

						let HasTheData = TheData.some(item => {
							return item.BluetoothProtocol == that.selectedDevice.BluetoothProtocol
						});

						if (!HasTheData) { // 不在存储数据中，存一遍
							TheData.push(that.selectedDevice)
							TheData.forEach((item, index) => {
								item.text = item.MeasureSpec
								item.value = index
								item.FilePath = that.Request.IPAgreement() + that.Request.serverIP() + item
									.FilePath
							});

							let TheIndex = TheData.length - 1;
							// console.log(TheData[TheIndex])

							that.$store.commit('QmsModule/ChangeAndSetStateData', {
								Name1: 'CheckHisValue',
								data: TheIndex,
								StorageName: 'CheckHisValue',
								StorageData: TheIndex
							});

							that.$store.commit('QmsModule/ChangeAndSetStateData', {
								Name1: 'HistoryDevice',
								data: TheData,
								StorageName: 'Agreement_History_DevicesList',
								StorageData: JSON.stringify(TheData)
							});
						} else {
							let TheIndex = 0
							// 如果在其中，那么替换原有的数据，并获取索引
							for (let i = 0; i < TheData.length; i++) {
								// that.selectedDevice
								// 查找协议名称一致的项
								if (TheData[i].BluetoothProtocol == that.selectedDevice.BluetoothProtocol) {
									// 替换原数组中的数据
									TheData[i] = that.selectedDevice;
									TheData[i].text = TheData[i].MeasureSpec
									TheData[i].value = i
									TheIndex = i
									break;
								}
							}
							// console.log(JSON.stringify(TheData))
							// vuex中实际是存了缓存的，所以应该直接存缓存
							that.$store.commit('QmsModule/ChangeAndSetStateData', {
								Name1: 'HistoryDevice',
								data: TheData,
								StorageName: 'Agreement_History_DevicesList',
								StorageData: JSON.stringify(TheData)
							});

							that.$store.commit('QmsModule/ChangeAndSetStateData', {
								Name1: 'CheckHisValue',
								data: TheIndex,
								StorageName: 'CheckHisValue',
								StorageData: TheIndex
							});

						}

					} else { // 未存储过数据
						Arr.push(that.selectedDevice)
						Arr.forEach((item, index) => {
							item.text = item.MeasureSpec
							item.value = index
						});

						that.$store.commit('QmsModule/ChangeAndSetStateData', {
							Name1: 'HistoryDevice',
							data: Arr,
							StorageName: 'Agreement_History_DevicesList',
							StorageData: JSON.stringify(Arr)
						});
					}

					// uni.setStorageSync('AgreementDevicesList')

					//关闭当前页面，返回到前台界面
					uni.navigateBack({
						success: function() {
							uni.$emit("callBackDeviceType", that.selectedDevice);
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: "请先选择一个设备协议",

					})
				}
			}
		}
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.content {
		/* 给顶部盒子安全高度 */
		padding-top: var(--status-bar-height);
		padding-left: 20px;
		padding-right: 20px;
		display: flex;
		flex-direction: column;

		.SiftBox {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 0;

			.SiftBtn {
				width: fit-content;
				height: 28px;
				line-height: 20px;
				padding: 4px 8px;
				border-radius: 8px;
				background: #f6f6f6;
				font-size: 12px;
			}
		}

		.u-image {
			margin: 0 auto !important;
		}

		.CommonCard {
			position: relative;
			padding: 20px 0 10px;
			background-color: #f6f6f6;
			border-radius: 12px;
			box-shadow: 1px 1px 7px -6px #ced4d5;

			.CheckIcon {
				position: absolute;
				top: 3px;
				right: 3px;
				display: block;
				padding: 3px;
				background: green;
				border-radius: 50px;
			}

			.TextBox {
				text-align: center;
				margin-top: 20rpx;
				padding: 0 10px;

				.Text {
					font-size: 12px;
					display: block;
					word-wrap: break-word;
					word-break: break-all;
					overflow: hidden;
				}
			}
		}

		// 品牌筛选弹窗
		.page {
			width: 100%;
			height: 100%;
		}

		.wraper {
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 100%;
		}

		.header {
			// background: rgb(8, 117, 94);
			color: #333;
			line-height: 60rpx;
			flex: 0 0 100rpx;
			/* 不放大不缩小固定100rpx */
			// background-color: pink;
		}

		.main {
			// height: 690rpx;
			position: relative;
		}

		.main-scroll {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}

		.main-list {
			// display: flex;
			// flex-wrap: wrap;
			// justify-content: space-between;
			margin-left: 2vw;
			margin-right: 2vw;

			// 品牌盒子
			.GridList {
				display: flex;
				flex-wrap: wrap;

				.GridCardBox {
					position: relative;
					box-shadow: 0 0 12px -9px #333;
					background-color: #fff;
					border-radius: 12px;
					overflow: hidden;
					width: 30%;
					margin: 5px;

					.textBox {
						text-align: center;
						padding: 4px 0;
						font-size: 14rpx;
					}
				}
			}
		}



		.footer {
			// line-height: 100rpx;
			flex: 0 0 100rpx;

		}


	}
</style>